//index.js
var {
  Client,
  Message
} = require('../../utils/paho-mqtt.js')
//获取当前系统日期和时间
var util = require('../../utils/util.js');
//获取应用实例
const app = getApp()
function getPost_lampData(data) {
  const payloadJson = {
    id: Date.now(),
    params: {
      lampState: data,
    },
    method: "thing.event.property.post"
  }
  return JSON.stringify(payloadJson);
}

function getPost_fanData(data) {
  const payloadJson = {
    id: Date.now(),
    params: {
      fanState: data,
    },
    method: "thing.event.property.post"
  }
  return JSON.stringify(payloadJson);
}
Page({
  data: {
    slider: 10,
    disable_slider: true,
    fanState: false,
    lampState: false,
    temp_src: "../images/wendu2.png",
    humid_src: "../images/shidu.png",
    light_src: "../images/light.png",
    fan_on: "../images/fanOn.png",
    fan_off: "../images/fanOff.png",
    lamp_on: "../images/lamp_ON.png",
    lamp_off: "../images/lamp_OFF.png",
    sun_src: "../images/liangdu.png",
    humid_unit:"../images/baifenhao.png",
    wendu_unit:"../images/sheshidu.png",
    wendu_data: "0",
    shidu_data: "0",
    light_data: "0",
    date: "2021/06/22 22:22:22"
  },
  onLoad: function (options) {
    var that = this
    that.doConnect(); //连接MQTT
    that.subscribe('/sys/a1w8Wn3cwTK/phone/thing/service/property/set', {
      qos: 0
    }); //订阅主题
  },
 //风扇控制
 fanControl: function (e) {
  var fanState = e.detail.value;
  this.setData({
    fanState: fanState
  })
  if (fanState == true) {
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_fanData(1), 0, false)
    console.log("pub:1")
  } else {
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_fanData(0), 0, false)
    console.log("pub:0")
  }
},
//LED灯控制
lampControl: function (e) {
  var lampState = e.detail.value;
  if (lampState) {
    this.setData({
      lampState: true,
      disable_slider:false,
      slider:10
    })
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_lampData(10), 0, false)
    console.log("pub:10")
  } else {
    this.setData({
      lampState: false,
      disable_slider:true,
    })
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_lampData(0), 0, false)
      console.log("pub:0")
  }
},
// LED灯亮度调节
click_slider:function(){
if(!this.data.lampState){
wx.showToast({
  title: 'LED灯未打开',
  icon: 'success',
  image:'../images/error2.png',
  duration: 2000
})
}
},
// 监测滑动条的值，并发布
changeSlider: function (e) {
  console.log("test1")
  var sliderValue = e.detail.value;
  if (sliderValue < 10) {
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_lampData(sliderValue), 0, false)
  } else {
    this.publish('/sys/a1w8Wn3cwTK/phone/thing/event/property/post', getPost_lampData(9), 0, false)
  }
},
// 发布主题
publish(topic, message, qos = 0, retained = false) {
  var client = this.data.client;
  if (client && client.isConnected()) {
    var message = new Message(message);
    message.destinationName = topic;
    message.qos = qos;
    message.retained = retained;
    return client.send(message);
  }
},
  doConnect() {
    var that = this;
    if (that.data.client && that.data.client.isConnected()) {
      wx.showToast({
        title: '不要重复连接'
      })
      return
    }
    var client = new Client('ws://a1w8Wn3cwTK.iot-as-mqtt.cn-shanghai.aliyuncs.com:443/', 'phone|securemode=3,signmethod=hmacsha1,timestamp=789|');
    client.connect({
      useSSL: false,
      userName: "phone&a1w8Wn3cwTK",
      password: "e2fa071cb5406e8995a10c63cba740456e1c077c",
      cleanSession: true,
      //reconnect: true, //设置断线重连，默认是断线不重连
      keepAliveInterval: 60,
      onSuccess: () => {
        wx.showToast({
          title: '连接成功'
        })
        that.data.client = client
        client.onMessageArrived = function (msg) {
          if (typeof that.data.onMessageArrived === 'function') {
            return that.data.onMessageArrived(msg)
          }
          var currenTime = util.formatTime(new Date());
          console.log(currenTime);
          var jsondata = JSON.parse(msg.payloadString);
          console.log("data:" + msg.payloadString);
          that.setData({
            wendu_data: jsondata['temperature'],
            shidu_data: jsondata['humidity'],
            light_data: jsondata['lightLux'],
            date: currenTime
          })
        }
        client.onConnectionLost = function (responseObject) {
          if (typeof that.data.onConnectionLost === 'function') {
            return that.data.onConnectionLost(responseObject)
          }
          if (responseObject.errorCode !== 0) {
            console.log("onConnectionLost:" + responseObject.errorMessage);
          }
        }
      }
    });
  },
  // 订阅主题
  subscribe(filter, subscribeOptions) {
    var client = this.data.client;
    if (client && client.isConnected()) {
      console.log("订阅成功！");
      return client.subscribe(filter, subscribeOptions);
    }
  },
 
  read_wendu: function () {
    wx.clearStorage()
    wx.setStorage({
      data: "wendu",
      key: 'name',
    })
    wx.switchTab({
      url: '../data/data',
    })
  },
  read_shidu: function () {
    wx.clearStorage()
    wx.setStorage({
      data: "shidu",
      key: 'name',
    })
    wx.switchTab({
      url: '../data/data',
    })
  },
  read_light: function () {
    wx.clearStorage()
    wx.setStorage({
      data: "light",
      key: 'name',
    })
    wx.switchTab({
      url: '../data/data'
    })
  },
  /////////////////////////////////////////////////////////////
  randomString: function (len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },

  setOnMessageArrived: function (onMessageArrived) {
    if (typeof onMessageArrived === 'function') {
      this.data.onMessageArrived = onMessageArrived
    }
  },
  setOnConnectionLost: function (onConnectionLost) {
    if (typeof onConnectionLost === 'function') {
      this.data.onConnectionLost = onConnectionLost
    }
  },

})